package com.opcode.costa.ui.dialogs;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.opcode.costa.R;
import com.opcode.nebulamobil.base.activities.FragmentActivityBase;
import com.opcode.nebulamobil.base.components.ButtonBase;
import com.opcode.nebulamobil.base.components.EditTextBase;
import com.opcode.nebulamobil.base.components.TextViewBase;
import com.opcode.nebulamobil.base.fragments.dialogfragments.DialogFragmentBase;
import com.opcode.nebulamobil.base.fragments.dialogfragments.RoundedProgressDialogBase;
import com.opcode.nebulamobil.base.interfaces.OnButtonBaseClickListener;
import com.opcode.nebulamobil.base.interfaces.ResponseListener;
import com.opcode.nebulamobil.information.ApplicationInfo;
import com.opcode.nebulamobil.information.dataforms.costadataforms.PersonalDataForm;
import com.opcode.nebulamobil.information.requests.costarequests.AuthenticationReq;
import com.opcode.nebulamobil.information.responses.JSONResponse;
import com.opcode.nebulamobil.information.responses.costaresponses.AuthenticationResp;
import com.opcode.nebulamobil.utility.JsonConverter;
import com.opcode.nebulamobil.utility.UniqueIdCreator;

/**
 * Bu dialog fragment kullanınınn seçilen personele ait şifreyi girmesi için hazırlanmıştır.
 * @author Okan ERDOĞAN
 * 11 Haz 2014
 */
public class LoginPasswordDialogFragment extends DialogFragmentBase implements ResponseListener{

	
	private View vi;
	private ButtonBase loginOkButton;
	private PersonalDataForm personalDataForm;
	private Intent intent;
	private TextViewBase personalNameInfo;
	private EditTextBase passwordEdittext;
	private Handler myHandler=null;
	private Runnable myRunnable=null;
	private boolean isAuthResult=false;
	
	private RoundedProgressDialogBase roundedProgressDialogBase;
	
	/**
	 * Fragment'in yapılandırıcında seçilen personele ait bilgiler ve 
	 * Şifre girildikten sonra açıllacak ekrana ait intent bilgisi parametre olarak alınır.
	 * @param personalDataForm
	 * @param intent
	 */
	public LoginPasswordDialogFragment(PersonalDataForm personalDataForm,Intent intent){
		this.personalDataForm=personalDataForm;
		this.intent=intent;
		this.roundedProgressDialogBase=new RoundedProgressDialogBase();
		ApplicationInfo.setResponseListener(this);
	}
	
	/**
	 * DialogFragment'a ait görsel öğeler bu method içerisinde ayarlanır.
	 */
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		this.vi = inflater.inflate(R.layout.login_password_dialog_fragment_layout, container,false);
		this.personalNameInfo=(TextViewBase) this.vi.findViewById(R.id.personal_name_info);
		this.loginOkButton=(ButtonBase) this.vi.findViewById(R.id.login_ok_button);
		this.passwordEdittext=(EditTextBase) this.vi.findViewById(R.id.password_edittext);
		passwordEdittext.setFocusableInTouchMode(true);
		passwordEdittext.setFocusable(true);
		this.showSoftInput(passwordEdittext);
		this.setCancelable(true);
		this.personalNameInfo.setText(personalDataForm.getPersonalName()+" "+personalDataForm.getPersonelSurName());
		
		myHandler = new Handler();
		
		loginOkButton.setOnButtonBaseClickListener(new OnButtonBaseClickListener(){

			@Override
			public void onButtonBaseClick(View v) {
				createRequest(personalDataForm.getPersonelID(),passwordEdittext.getText().toString());				
			}		
		});
		
		myRunnable = new Runnable() {
			   public void run() {
				   if(isAuthResult){
						hideSoftInput(); 
				   }else{
					   passwordEdittext.setText("");
					   Toast.makeText(getActivity(), "Kullanıcı adı veya şifreniz hatalı", Toast.LENGTH_SHORT).show();
					   if((FragmentActivityBase)getActivity()!=null){
							((FragmentActivityBase)getActivity()).closeGeneralDialog(roundedProgressDialogBase, "LOGIN_PASSWORD_PROGRESS_DIALOG");

						} 
				   } 
			   }
			};
		return this.vi;
	}
	
	public void onResume(){
		super.onResume();
	}
	
	private void updateGUI() {
		myHandler.post(myRunnable);
	}
	
	/**
	 * Kullanıcı adı ve şifre girildikten sonra bu metod çağrılır ve sunucuya oturum açıllmak istenir.
	 * @param personalId
	 * @param passWord
	 */
	public void createRequest(long personalId,String passWord){
		//((FragmentActivityBase)getActivity()).showGeneralDialog(this.roundedProgressDialogBase, "LOGIN_PASSWORD_PROGRESS_DIALOG");
		AuthenticationReq authenticationReq=new AuthenticationReq();
		authenticationReq.setType("AuthenticationReq");
		authenticationReq.setPersonalId(personalId);
		authenticationReq.setPassword(passWord);
		authenticationReq.setRequestId(UniqueIdCreator.createUniqueID());
		
		ApplicationInfo.getRequestListener().jsonRequestCame(JsonConverter.toJsonString(authenticationReq));
	}
	

	
	/**
	 * Sunucuya gönderilen oturum açma talebi olumsuzsa uyarı mesajı çıkar. Eğer olumluysa uygulamaya giriş yapılmış olunur.
	 */
	@Override
	public void responseCame(String response) {
		JSONResponse responseObject=(JSONResponse) JsonConverter.fromJsonString(response, JSONResponse.class);
		
		if(responseObject.getType().equals("AuthenticationResp")){
			AuthenticationResp authenticationResp=(AuthenticationResp) JsonConverter.fromJsonString(response, AuthenticationResp.class);

			if(authenticationResp.isAuthResult()){
				this.isAuthResult=true;
				updateGUI();

				if((FragmentActivityBase)getActivity()!=null){
					((FragmentActivityBase)getActivity()).createSharedPreferencesManager("sharedpreferences",getActivity());

					((FragmentActivityBase)getActivity()).writeToSharedPreferences("personalDataForm", JsonConverter.toJsonString(personalDataForm));

					/*if((FragmentActivityBase)getActivity()!=null){
						((FragmentActivityBase)getActivity()).closeGeneralDialog(roundedProgressDialogBase, "LOGIN_PASSWORD_PROGRESS_DIALOG");
					}*/
					dismiss();
					if(!isAdded()) {
						Log.i("LoginPasswordDialogFragment", "LoginPasswordDialogFragment aktiviteye eklenmemiş.");
					    return;
					}else{
						startActivity(intent);
					}
				}
			}else{
				this.isAuthResult=false;

				updateGUI();
			}
		}
		
		
	}
}
